package org.example.com.editor.command.editorCommand;

import org.example.com.editor.command.Command;
import org.example.com.editor.editor.TextEditor;
import org.example.com.editor.logger.LogManager;
import org.example.com.editor.ui.ConsoleUI;
import org.example.com.editor.workspace.Workspace;

import java.io.IOException;
import java.util.List;

public class ShowCommand implements Command {
    private final LogManager logManager;

    public ShowCommand(LogManager logManager) {
        this.logManager = logManager;
    }


    @Override
    public void execute(Workspace workspace, ConsoleUI ui) {
        // 校验是否有活动文本编辑器
        TextEditor editor = (TextEditor) workspace.getActiveEditor();
        if (editor == null) {
            ui.printError("没有活动的文本文件，请先打开或新建文件");
            return;
        }

        if (!editor.getFilePath().endsWith(".txt")){
            ui.printError("当前命令仅用于文本文件！");
            return;
        }

        List<String> content = editor.getContent();

        // 解析命令参数
        String[] args = ui.getCommandArgs();
        int startLine = 1;
        int endLine = content.size();

        if (args.length == 2) {
            String range = args[1];
            String[] lineRange = range.split(":", 2);
            if (lineRange.length != 2) {
                ui.printError("范围格式错误，请使用 [startLine:endLine]（例如：show 2:5）");
                return;
            }

            try {
                startLine = Integer.parseInt(lineRange[0]);
                endLine = Integer.parseInt(lineRange[1]);
            } catch (NumberFormatException e) {
                ui.printError("行号必须为整数（例如：show 2:5）");
                return;
            }

            // 校验行号边界
            if (startLine < 1) {
                ui.printError("起始行号不能小于1");
                return;
            }
            if (endLine > content.size()) {
                ui.printError("结束行号越界！当前文件总行数为 " + content.size());
                return;
            }
            if (startLine > endLine) {
                ui.printError("起始行号不能大于结束行号");
                return;
            }
        } else if (args.length > 2) {
            ui.printError("用法错误！支持两种格式：");
            ui.printError("1. 显示全文：show");
            ui.printError("2. 显示指定范围：show [startLine:endLine]（例如：show 2:5）");
            return;
        }

        // 显示文本内容
        for (int i = startLine - 1; i <= endLine - 1; i++) {
            String line = content.get(i);
            ui.printInfo( (i + 1) +" " + line );
        }

        try {
            logManager.onCommandExecuted(workspace.getActiveFile(), args);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String getName() {
        return "show";
    }
}
